<?php
##############################################
#
#   filecomment
# @ Time : 2017-10-1 - ����10:19:11
# @ Author : JiangYongWei <1085562810@qq.com>
# @ Encoding : UTF-8 language  : PHP
#
##############################################
namespace Common;

class Restful{
	/**
	 * User
	 */
	private $_user;

	/**
	 * Article
	 */
	private $_article;

	/**
	 * 请求方法
	 */
	private $_requestMethod;

	/**
	 * 资源名称
	 */
	private $_resourceName;

	/**
	 * 请求ID
	 */
	private $_id;

	/**
	 * 允许请求的资源列表
	 *
	 * @var        array
	 */
	private $_allowResources = ['Users','Articles'];

	/**
	 * 允许请求的方法
	 *
	 * @var        array
	 */
	private $_allowRequestMethods = ['GET','POST','PUT','DELETE','OPTIONS'];

	/**
	 * http请求状态码
	 *
	 * @var        array
	 */
	private $_statusCodes = [
	200 => 'OK',
	204 => 'No Content',
	400 => 'Bad Request',
	401 => 'Unauthorized',
	403 => 'Forbidden',
	404 => 'Not Found',
	405 => 'Method Not Allowed',
	500 => 'Server Internet Error'
			];
	
	/**
	 * 构造方法
	 *
	 * @param      User     $_user     The user
	 * @param      Article  $_article  The article
	 */
	public function __construct(User $_user,Article $_article){
		$this->_user 	= $_user;
		$this->_article = $_article;
	}
	
	public function run(){
		try{
			$this->_setupRequestMethod();
			$this->_setupResource();
			$this->_setId();
			if($this->_resourceName == 'Users'){
				return $this->_json($this->_handleUser());
			}else{
				return $this->_json($this->_handleArticle());
			}
		}catch(Exception $e){
			$this->_json(['error'=>$e->getMessage()],$e->getCode());
		}
	
	}
	
	/**
	 * 初始化请求方法
	 */
	private function _setupRequestMethod(){
		$this->_requestMethod = $_SERVER['REQUEST_METHOD'];
		if(!in_array($this->_requestMethod, $this->_allowRequestMethods)){
			throw new Exception("请求方法不被允许", 405);
		}
	}
	
	/**
	 * 初始化请求资源
	 */
	private function _setupResource(){
		$path = $_SERVER['PATH_INFO'];
		$params = explode('/',$path);
		$this->_resourceName = $params[1];
		if(!in_array($this->_resourceName, $this->_allowResources)){
			throw new Exception("请求资源不被允许", 405);
		}
		if(!empty($params[2])){
			$this->_id = $params[2];
		}
	}
	
	/**
	 * 输出json
	 *
	 * @param      array  $array  The array
	 */
	private function _json($array,$code=0){
		if($array === null && $code === 0){
			$code = 204;
		}
		if($array !== null && $code === 0){
			$code = 200;
		}
		header("HTTP/1.1 ".$code."  ".$this->_statusCodes[$code]);
		header("Content-Type=application/json;charset=UTF-8 ");
		if($array !== null){
			echo  json_encode($array,JSON_UNESCAPED_UNICODE);
		}
		exit();
	}
	
}